import 'package:flutter/material.dart';

/// XH弹幕工具类
class XhDanmuUtils {
  XhDanmuUtils._();
  
  /// 计算文本尺寸
  static Size calculateTextSize({
    required String text,
    required TextStyle style,
    double maxWidth = double.infinity,
    int? maxLines,
  }) {
    final textPainter = TextPainter(
      text: TextSpan(text: text, style: style),
      textDirection: TextDirection.ltr,
      maxLines: maxLines,
    );
    
    textPainter.layout(maxWidth: maxWidth);
    return textPainter.size;
  }
  
  /// 计算弹幕文本宽度（包含容器内边距）
  static double calculateDanmuWidth({
    required String text,
    required double fontSize,
    required FontWeight fontWeight,
    required EdgeInsets padding,
  }) {
    final textStyle = TextStyle(
      fontSize: fontSize,
      fontWeight: fontWeight,
    );
    
    final textSize = calculateTextSize(
      text: text,
      style: textStyle,
    );
    
    return textSize.width + padding.horizontal;
  }
  
  /// 生成随机颜色
  static Color getRandomColor(List<Color> colors) {
    if (colors.isEmpty) return Colors.white;
    final now = DateTime.now();
    final index = now.millisecond % colors.length;
    return colors[index];
  }
  
  /// 验证弹幕文本
  static bool isValidDanmuText(String text) {
    return text.trim().isNotEmpty && text.length <= 100;
  }
  
  /// 格式化时间显示
  static String formatTime(double seconds) {
    final minutes = (seconds / 60).floor();
    final remainingSeconds = (seconds % 60);
    return '${minutes.toString().padLeft(2, '0')}:${remainingSeconds.toStringAsFixed(1).padLeft(4, '0')}';
  }
  
  /// 计算弹幕完整通过屏幕所需的时间
  static double calculateTransitTime({
    required double containerWidth,
    required double danmuWidth,
    required double speed,
  }) {
    final totalDistance = containerWidth + danmuWidth;
    return totalDistance / speed;
  }
  
  /// 限制数值范围
  static double clamp(double value, double min, double max) {
    if (value < min) return min;
    if (value > max) return max;
    return value;
  }
  
  /// 线性插值
  static double lerp(double a, double b, double t) {
    return a + (b - a) * clamp(t, 0.0, 1.0);
  }
}
